package com.gnerv.battle.boot.framework.service.impl;

import com.gnerv.battle.boot.framework.common.exception.BattleBusinessException;
import com.gnerv.battle.boot.framework.service.CurrentAccountService;
import com.gnerv.battle.boot.framework.service.PasswordService;
import com.gnerv.battle.boot.framework.model.bo.ManageAccountBO;
import com.gnerv.battle.boot.framework.model.dto.ManageAccountDTO;
import com.gnerv.battle.boot.framework.model.entity.ManageAccount;
import com.gnerv.battle.boot.framework.repository.ManageAccountRepository;
import com.gnerv.battle.boot.framework.service.ManageAccountService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.gnerv.battle.boot.framework.common.tools.PageTools.limitSize;
import static com.gnerv.battle.boot.framework.common.tools.PageTools.limitStart;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
@AllArgsConstructor
public class ManageAccountServiceImpl implements ManageAccountService {

    private final ManageAccountRepository manageAccountRepository;
    private final PasswordService passwordService;
    private final CurrentAccountService currentAccountService;

    @Override
    public boolean create(ManageAccountBO manageAccountBO) {
        boolean exist = manageAccountRepository.isExist(manageAccountBO.getUsername());
        if (exist) {
            throw new BattleBusinessException("username already exist !");
        }
        ManageAccount manageAccount = manageAccountBO.toCreateManageAccount();
        manageAccount.setPassword(passwordService.encrypt(manageAccount.getPassword()));
        manageAccount.setCreator(currentAccountService.ukId());
        manageAccountRepository.insert(manageAccount);
        return true;
    }

    @Override
    public boolean deleteByUkId(String ukId) {
        // 账户设置为逻辑删除
        manageAccountRepository.updateDeletedByUkId(ukId);
        return true;
    }

    @Override
    public boolean updateByUkId(ManageAccountBO manageAccountBO) {
        ManageAccount manageAccount = manageAccountBO.toUpdateManageAccount();
        manageAccountRepository.updateByUkId(manageAccount);
        return true;
    }

    @Override
    public ManageAccountDTO selectByUkId(String ukId) {
        return manageAccountRepository.selectByUkId(ukId);
    }

    @Override
    public List<ManageAccountDTO> listByUsername(String username, Integer page, Integer size) {
        return manageAccountRepository.listByUsername(username, limitStart(page, size), limitSize(size));
    }

    @Override
    public long countByUsername(String username) {
        return manageAccountRepository.countByUsername(username);
    }

}
